<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<WtmSearcher v-if="searchBar" v-model="searchData" @search="getTableData" :showToggleAdvanced="true" :defaultExpandAdvanced="false">
			<template #primary="{ showAdvanced }">
				<el-row :gutter="15">
					<!-- ===== 核心搜索条件（常用） ===== -->
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="LocationId_FormItem" prop="LocationId">
							<template #label>
								<WtmLabelTooltip label="库位" tooltip="存储库位" />
							</template>
							<el-select v-model="searchData.LocationId" :data="stateData.AllSysWarehouseLocations" clearable>
								<el-option v-for="item in stateData.AllSysWarehouseLocations" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
							></el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="MaterialName_FormItem" prop="MaterialName">
							<template #label>
								<WtmLabelTooltip label="物料名称" tooltip="物料名称" />
							</template>
							<el-input v-model="searchData.MaterialName" clearable placeholder="请输入物料名称"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="MaterialCode_FormItem" prop="MaterialCode">
							<template #label>
								<WtmLabelTooltip label="物料编码" tooltip="物料编码" />
							</template>
							<el-input v-model="searchData.MaterialCode" clearable placeholder="请输入物料编码"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="SkuName_FormItem" prop="SkuName">
							<template #label>
								<WtmLabelTooltip label="规格名称" tooltip="规格名称" />
							</template>
							<el-input v-model="searchData.SkuName" clearable placeholder="请输入规格名称"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="SkuCode_FormItem" prop="SkuCode">
							<template #label>
								<WtmLabelTooltip label="规格编码" tooltip="规格编码" />
							</template>
							<el-input v-model="searchData.SkuCode" clearable placeholder="请输入规格编码"></el-input>
						</el-form-item>
					</el-col>

					<!-- ===== 高级搜索条件（可展开） ===== -->
					<template v-if="showAdvanced">
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="ErpId_FormItem" prop="ErpId">
								<template #label>
									<WtmLabelTooltip label="ERP编号" tooltip="ERP系统中的编号" />
								</template>
								<el-input v-model="searchData.ErpId" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="BatchNumber_FormItem" prop="BatchNumber">
								<template #label>
									<WtmLabelTooltip label="批次号" tooltip="物料批次号" />
								</template>
								<el-input v-model="searchData.BatchNumber" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="PartnerId_FormItem" prop="PartnerId">
								<template #label>
									<WtmLabelTooltip label="供应商" tooltip="物料供应商" />
								</template>
								<el-select v-model="searchData.PartnerId" :data="stateData.AllSysPartners" clearable>
									<el-option v-for="item in stateData.AllSysPartners" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="StoreType_FormItem" prop="StoreType">
								<template #label>
									<WtmLabelTooltip label="存储类型" tooltip="存储类型" />
								</template>
								<el-select v-model="searchData.StoreType" clearable>
									<el-option key="受托代销" value="受托代销" label="受托代销"></el-option>
									<el-option key="客户来料" value="客户来料" label="客户来料"></el-option>
									<el-option key="客户寄存" value="客户寄存" label="客户寄存"></el-option>
									<el-option key="委托代销" value="委托代销" label="委托代销"></el-option>
									<el-option key="设备" value="设备" label="设备"></el-option>
									<el-option key="普通" value="普通" label="普通"></el-option>
									<el-option key="备品" value="备品" label="备品"></el-option>
									<el-option key="借出" value="借出" label="借出"></el-option>
									<el-option key="赠品" value="赠品" label="赠品"></el-option>
									<el-option key="其它" value="其它" label="其它"></el-option>
									<el-option key="借入" value="借入" label="借入"></el-option>
									<el-option key="供应商寄存" value="供应商寄存" label="供应商寄存"></el-option
								></el-select>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</template>
		</WtmSearcher>

		<div v-if="toolbar">
			<WtmButton
				v-auth="'/api/SysWarehouseStock/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysWarehouseStock/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton v-auth="'/api/SysWarehouseStock/Sync'" type="primary" button-text="数据同步" @click="onSync()" />
			<WtmButton
				v-auth="'/api/SysWarehouseStock/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/SysWarehouseStock/ExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
		</div>

		<WtmTable ref="tableRef" v-bind="tableData" class="table-operation-area">
			<template #operation>
				<el-table-column :label="$t('message._system.common.vm.operate')" min-width="180" align="center" class-name="operation-column">
					<template v-slot="scope">
						<div class="operation-container">
							<WtmButton
								v-auth="'/api/SysWarehouseStock/Edit'"
								:is-text="true"
								icon="fa fa-pencil-square"
								type="warning"
								:button-text="$t('message._system.common.vm.edit')"
								@click="OnEditRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysWarehouseStock/{id}'"
								:is-text="true"
								icon="fa fa-info-circle"
								type="info"
								:button-text="$t('message._system.common.vm.detail')"
								@click="OnDetailsRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysWarehouseStock/BatchDelete'"
								icon="fa fa-trash"
								type="danger"
								:button-text="$t('message._system.common.vm.delete')"
								:confirm="$t('message._system.common.vm.deletetip')"
								:is-text="true"
								@click="onDelete(scope.row)"
							/>
						</div>
					</template>
				</el-table-column>
			</template>
		</WtmTable>
	</div>
</template>

<script setup lang="ts" name="库存;true;HengTong.Areas.SupplyChain.Controllers;SysWarehouseStock">
import ElMessage from 'element-plus/es/components/message/index';
import { defineAsyncComponent, reactive, ref, getCurrentInstance, onMounted, computed } from 'vue';
import { SysWarehouseStockApi as api } from '/@/views/supplychain/syswarehousestock/api';
import { ISysWarehouseStockView, ISysWarehouseStockQuery } from '/@/views/supplychain/syswarehousestock/api/interface';
import other from '/@/utils/other';
import { IViewModel, ISysSelectType } from '/@/types/common';

const ci = getCurrentInstance() as any;
const loading = ref(false);
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 默认筛选 */
		filters?: ISysWarehouseStockQuery;
		/** 主表ID */
		entityId?: string | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: true,
		filters: () => ({}),
		entityId: null,
	}
);

const stateData = reactive({
	AllSysWarehouseLocations: [] as ISysSelectType[],
	AllSysMaterials: [] as ISysSelectType[],
	AllSysMaterialSkus: [] as ISysSelectType[],
	AllSysPartners: [] as ISysSelectType[],
});

const searchData = ref<ISysWarehouseStockQuery>({
	LocationId: null,
	MaterialId: null,
	MaterialName: null,
	MaterialCode: null,
	SkuId: null,
	SkuName: null,
	SkuCode: null,
	ErpId: null,
	BatchNumber: null,
	PartnerId: null,
	StoreType: null,
});

// 定义变量内容
const tableRef = ref();
const tableData = ref({
	// 列表数据（必传）s
	data: [],
	// 表头内容（必传，注意格式）
	header: [
		{ title: '物料', key: 'MaterialName', type: 'text', isCheck: true },
		{ title: '物料SKU', key: 'SkuName', type: 'text', isCheck: true },
		{ title: '数量', key: 'Quantity', type: 'text', isCheck: true },
		{ title: '库位', key: 'LocationName', type: 'text', isCheck: true },
		{ title: '批次号', key: 'BatchNumber', type: 'text', isCheck: true },
		{ title: '供应商', key: 'PartnerName', type: 'text', isCheck: true },
		{ title: '存储类型', key: 'StoreType', type: 'text', isCheck: true },
		{ title: 'ERP编号', key: 'ErpId', type: 'text', isCheck: true },
	],
	// 配置项（必传）
	config: {
		total: 0, // 列表总数
		loading: true, // loading 加载
		isSerialNo: true, // 是否显示表格序号
		isSelection: true, // 是否显示表格多选
		isOperate: props.isDisabled, // 是否显示表格操作栏
	},
});
// 初始化表格数据
const getTableData = async () => {
	try {
		await tableRef.value.doSearch(api().search, searchData.value);
	} catch (error) {
		other.setFormError(ci, error);
	}
};
const OnCreateClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.add'), CreateDialog, null, getTableData);
};

const OnEditRowClick = (row: ISysWarehouseStockView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.edit'), EditDialog, row, getTableData);
};

const OnDetailsRowClick = (row: ISysWarehouseStockView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.detail'), DetailsDialog, row, getTableData);
};

// 删除
const onDelete = (row: ISysWarehouseStockView) => {
	const ids = [row.ID] as (string | number)[];
	api()
		.delete(ids)
		.then(() => {
			getTableData();
		});
};

//批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysWarehouseStockView) => x.ID) as (string | number)[];
	if (selectedIds && selectedIds.length > 0) {
		try {
			await api().delete(selectedIds);
			// 先清除选择状态
			tableRef.value?.clearSelection();
			// 再重新获取数据
			getTableData();
		} catch (error) {
			ElMessage.error(ci.proxy.$t('message._system.common.vm.error'));
		}
	} else {
		ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
	}
};
// 添加计算属性判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

const OnImportClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.import'), ImportDialog, null, getTableData);
};

const onExport = () => {
	const selected = tableRef.value.getSelectedRows();
	if (selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};

const onSync = () => {
	api()
		.sync()
		.then(() => {
			getTableData();
		})
		.catch((error) => {
			other.setFormError(ci, error);
		});
};

// 页面加载时
onMounted(() => {
	loading.value = true;
	const promises: Promise<any>[] = [
		other.getSelectList('/api/SysWarehouseStock/GetSysWarehouseLocations', [], false).then((x) => (stateData.AllSysWarehouseLocations = x)),
		other.getSelectList('/api/SysWarehouseStock/GetSysMaterials', [], false).then((x) => (stateData.AllSysMaterials = x)),
		other.getSelectList('/api/SysWarehouseStock/GetSysMaterialSkus', [], false).then((x) => (stateData.AllSysMaterialSkus = x)),
		other.getSelectList('/api/SysWarehouseStock/GetSysPartners', [], false).then((x) => (stateData.AllSysPartners = x)),

		getTableData(),
	];
	Promise.allSettled(promises).finally(() => {
		loading.value = false;
	});
});
</script>
